package com.example.sunmiv1.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.PurchaseOrderAdapter;
import com.example.sunmiv1.entity.StorePurchaseOrderInfo;
import com.example.sunmiv1.entity.StoreWarehouseInfo;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

// 採購管理.採購單
public class PurchaseOrderActivity extends Activity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.purchaseOrder_type)
    Spinner purchaseOrderType;
    @BindView(R.id.purchaseOrder_warehouse)
    Spinner purchaseOrderWarehouse;
    @BindView(R.id.purchaseOrder_supplies)
    Spinner purchaseOrderSupplies;
    @BindView(R.id.purchaseOrder_startTime)
    TextView purchaseOrderStartTime;
    @BindView(R.id.purchaseOrder_endTime)
    TextView purchaseOrderEndTime;
    @BindView(R.id.purchaseOrder_edit)
    EditText purchaseOrderEdit;
    @BindView(R.id.search_purchaseOrder)
    ImageView searchPurchaseOrder;
    @BindView(R.id.purchaseOrder_add)
    Button purchaseOrderAdd;
    @BindView(R.id.purchaseOrder_listView)
    PullToRefreshListView purchaseOrderListView;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;


    private Context context;
    private ACache aCache;
    private Intent intent;
    private LoadingDialog loadingDialog;

    private int page = 1;//頁碼

    private List<String> typeList = new ArrayList<>();//類型集合
    private int typeIndex = 0;//選擇的類型下標

    private StoreWarehouseInfo storeWarehouseInfo;
    private List<String> warehouseNameList = new ArrayList<>();//倉庫名稱集合
    private List<StoreWarehouseInfo.WarehouseListBean> warehouseList = new ArrayList<>();//倉庫集合
    private int warehouseIndex = 0;//選擇的倉庫下標

    private List<String> suppliesNameList = new ArrayList<>();//供應商名稱集合
    private List<StoreWarehouseInfo.SupplierListBean> suppliesList = new ArrayList<>();//供應商集合
    private int suppliesIndex = 0;//選擇的供應商下標

    private StorePurchaseOrderInfo storePurchaseOrderInfo;
    private List<StorePurchaseOrderInfo.DataBean> orderList = new ArrayList<>();
    private PurchaseOrderAdapter purchaseOrderAdapter;

    private String userType;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    setPurchaseOrderAdapter();
                    break;
                case 2:
                    setPurchaseOrderAdapter();
                    break;
                case 3:
                    setWarehouseAdapter();
                    setSuppliesAdapter();
                    break;
                case 4:
                    setWarehouseAdapter();
                    setSuppliesAdapter();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_purchase_order);
        ButterKnife.bind(this);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        userType=aCache.getAsString("userType");
        titleTitle.setText(R.string.purchaseOrderTitle);
        initData();
    }

    private void initData() {
        typeList.add(getString(R.string.typeList1));
        typeList.add(getString(R.string.typeList2));
        typeList.add(getString(R.string.typeList3));
        purchaseOrderAdapter = new PurchaseOrderAdapter(context, orderList);
        purchaseOrderListView.setAdapter(purchaseOrderAdapter);
        getStoreWarehouseInfo();
        setTypeAdapter();
        initListener();
    }

    private void initListener() {
        purchaseOrderAdapter.Click((type, index) -> {
            switch (type){
                case 1:  //編輯
                    intent = new Intent(context, PurchaseOrderAddActivity.class);
                    intent.putExtra("id", orderList.get(index).getId());
                    intent.putExtra("isedit" ,true);
                    if ("2".equals(userType)) {//店長
                        intent.putExtra("type", 1);
                    } else {//商戶
                        intent.putExtra("type", 3);
                    }
                    startActivity(intent);
                    break;
                case 2:  //入庫
                    new AlertDialog.Builder(this).setTitle("入庫操作")//設置對話框標題
                            .setMessage("確定要入庫？")//設置顯示的內容
                            .setPositiveButton("確定", (dialog, which) -> {
                                warehousing(orderList.get(index).getId());
                            })
                            .setNegativeButton("取消", (dialog, which) -> {
                                    }
                            ).show();//顯示此對話框
                    break;
                case 3:  //詳情
                    intent = new Intent(context, AllocationDetailActivity.class);
                    intent.putExtra("id", orderList.get(index).getId());
                    if ("2".equals(userType)) {//店長
                        intent.putExtra("type", 3);
                    } else {//商戶
                        intent.putExtra("type", 4);
                    }
                    startActivity(intent);
                    break;
            }
        });
        purchaseOrderType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                typeIndex = position;
                getStorePurchaseOrder();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        purchaseOrderWarehouse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                warehouseIndex = position;
                getStorePurchaseOrder();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        purchaseOrderSupplies.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                suppliesIndex = position;
                getStorePurchaseOrder();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        purchaseOrderListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                orderList.clear();
                setPurchaseOrderAdapter();
                getStorePurchaseOrder();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getStorePurchaseOrder();
            }
        });
    }

    /**
     * 類型適配器
     */
    private void setTypeAdapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_drop, typeList);
        arrayAdapter.setDropDownViewResource(R.layout.item_drops);
        purchaseOrderType.setAdapter(arrayAdapter);
    }

    /**
     * 採購倉適配器
     */
    private void setWarehouseAdapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_drop, warehouseNameList);
        arrayAdapter.setDropDownViewResource(R.layout.item_drops);
        purchaseOrderWarehouse.setAdapter(arrayAdapter);
    }

    /**
     * 供應倉適配器
     */
    private void setSuppliesAdapter() {
        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_drop, suppliesNameList);
        arrayAdapter.setDropDownViewResource(R.layout.item_drops);
        purchaseOrderSupplies.setAdapter(arrayAdapter);
    }

    private void setPurchaseOrderAdapter() {
        if (purchaseOrderAdapter == null) {
            purchaseOrderAdapter = new PurchaseOrderAdapter(context, orderList);
            purchaseOrderListView.setAdapter(purchaseOrderAdapter);
        } else {
            purchaseOrderAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getStorePurchaseOrder();
    }
    @OnClick({R.id.title_back,R.id.btn_to_top, R.id.purchaseOrder_startTime, R.id.purchaseOrder_endTime,  R.id.search_purchaseOrder, R.id.purchaseOrder_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.btn_to_top:
                purchaseOrderListView.getRefreshableView().setSelection(0);
                break;
            case R.id.purchaseOrder_startTime:
                Tools.getDateFromDatePickerDialog(purchaseOrderStartTime);
                getStorePurchaseOrder();
                break;
            case R.id.purchaseOrder_endTime:
                Tools.getDateFromDatePickerDialog(purchaseOrderEndTime);
                getStorePurchaseOrder();
                break;
            case R.id.search_purchaseOrder:
                page = 1;
                orderList.clear();
                setPurchaseOrderAdapter();
                getStorePurchaseOrder();
                break;
            case R.id.purchaseOrder_add:
                intent = new Intent(context, PurchaseOrderAddActivity.class);
                if ("2".equals(userType)) {//店長
                    intent.putExtra("type", 0);
                } else {//商戶
                    intent.putExtra("type", 2);
                }
                startActivity(intent);
                break;
        }
    }

    /**
     * 獲取採購倉與供貨商信息
     */
    private void getStoreWarehouseInfo() {
        JSONObject jsonObject = new JSONObject();
            String url = "";
            if ("2".equals(userType)) {
                url = Common.STORE_WAREHOUSE_INFO;
            } else {
                url = Common.MER_WAREHOUSE_INFO;
            }
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
            HttpUtils.post(context, url, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    storeWarehouseInfo = GsonUtils.JsonToBean(text, StoreWarehouseInfo.class);
                    Message msg = new Message();
                    if (storeWarehouseInfo.getStatus() == 1) {
                        warehouseList.clear();
                        warehouseNameList.clear();
                        suppliesList.clear();
                        suppliesNameList.clear();
                        warehouseList.add(new StoreWarehouseInfo.WarehouseListBean("", "全部倉庫"));
                        warehouseNameList.add("全部倉庫");
                        for (StoreWarehouseInfo.WarehouseListBean warehouseListBean : storeWarehouseInfo.getWarehouseList()) {
                            warehouseList.add(warehouseListBean);
                            warehouseNameList.add(warehouseListBean.getName());
                        }
                        suppliesList.add(new StoreWarehouseInfo.SupplierListBean("", "全部供應倉"));
                        suppliesNameList.add("所有供貨商");
                        for (StoreWarehouseInfo.SupplierListBean supplierListBean : storeWarehouseInfo.getSupplierList()) {
                            suppliesList.add(supplierListBean);
                            suppliesNameList.add(supplierListBean.getSupplier_name());
                        }
                        msg.what = 3;
                    } else {
                        warehouseList.clear();
                        warehouseNameList.clear();
                        suppliesList.clear();
                        suppliesNameList.clear();
                        warehouseList.add(new StoreWarehouseInfo.WarehouseListBean("", "全部倉庫"));
                        warehouseNameList.add("全部倉庫");
                        suppliesList.add(new StoreWarehouseInfo.SupplierListBean("", "全部供應倉"));
                        suppliesNameList.add("所有供貨商");
                        msg.what = 4;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });

    }

    /**
     * 獲取採購單列表
     */
    private void getStorePurchaseOrder() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();

            String url = "";
            if ("2".equals(userType)) {
                url = Common.STORE_PURCHASE_ORDER;
            } else {
                url = Common.MER_PURCHASE_ORDER;
            }
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("page", page);
            jsonObject.put("limit", 20);
            jsonObject.put("type",String.valueOf(typeIndex));
            jsonObject.put("order_number", purchaseOrderEdit.getText().toString().trim());
            jsonObject.put("supplier_id", suppliesIndex == 0 ? "" : suppliesList.get(suppliesIndex).getId());
            jsonObject.put("warehouse_id", warehouseIndex == 0 ? "" : warehouseList.get(warehouseIndex).getId());
            jsonObject.put("start_time", purchaseOrderStartTime.getText().toString().trim());
            jsonObject.put("end_time", purchaseOrderEndTime.getText().toString().trim());
            jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            jsonObject.put("user_type", aCache.getAsString("userType"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
            HttpUtils.post(context, url, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    purchaseOrderListView.onRefreshComplete();
                    storePurchaseOrderInfo = GsonUtils.JsonToBean(text, StorePurchaseOrderInfo.class);
                    Message msg = new Message();
                    if (storePurchaseOrderInfo.getStatus() == 1) {
                        orderList.clear();
                        orderList.addAll(storePurchaseOrderInfo.getData());
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                    purchaseOrderListView.onRefreshComplete();
                }
            });

    }

    /**
     * 入庫
     */
    private void warehousing(String id) {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();

            String url = "";
            if ("2".equals(userType)) {
                url = Common.STORE_WAREHOUSE_OPERATION;
            } else if ("1".equals(userType)) {
                url = Common.MER_WAREHOUSE_OPERATION;
            }
        try {
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("id", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
            HttpUtils.post(context, url, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            page = 1;
                            orderList.clear();
                            setPurchaseOrderAdapter();
                            getStorePurchaseOrder();
                        } else {
                            Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });

    }
}
